package com.qianfeng.android.baoman.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

/**
 * Created by maxiaoyu on 2015/2/3.
 * User:Maxiaoyu
 * Date:2015/2/3
 * Email:731436452@qq.com
 */
public final class StreamUtil {

    /**
     * 工具类不能继承，不能实例化
     */
    private StreamUtil() {
    }

    /**
     * 关闭输入流，输出流
     *
     * @param stream
     */
    public static void close(Object stream) {
        if (stream != null) {
            try {
                if (stream instanceof InputStream) {
                    ((InputStream) stream).close();
                } else if (stream instanceof OutputStream) {
                    ((OutputStream)stream).close();
                } else if (stream instanceof Reader) {
                    ((Reader)stream).close();
                } else if (stream instanceof Writer) {
                    ((Writer)stream).close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 将输入流读取到字节数组中
     *
     * @param inputStream
     * @return
     * @throws java.io.IOException
     */
    public static byte[] readStream(InputStream inputStream) throws IOException {
        byte[] ret = null;
        if (inputStream != null) {
            //这个buf必须释放
            ByteArrayOutputStream bout = null;
            int length = readStream(inputStream, bout);
            if (length != 0) {
                //bout.toByteArray(); 再返回的时候，会将内部的数组复制一份，然后返回给ret，
                // 这个时候，两份考本，
                ret = bout.toByteArray();
            }

            close(bout);
            bout = null;
        }
        return ret;
    }

    /**
     * 持续读取in中数据，将数据直接写出到out中
     *
     * @param in  输入流
     * @param out 输出流
     * @return 字节数组长度
     */
    public static int readStream(InputStream in, OutputStream out) throws IOException {
        int ret = 0;
        if (in != null && out != null) {
            byte[] buf = new byte[128];
            int len;
            while (true) {
                len = in.read(buf);

                if (len == -1) {
                    break;
                }
                out.write(buf, 0, len);
                ret += len;
            }
            buf = null;
        }
        return ret;
    }

}